package com.frogs.ucenter.v1.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.frogs.api.wechat.util.TemplateUtil;
import com.frogs.framework.util.PageList;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.component.RequestApiHelper;
import com.frogs.ucenter.dao.UserAttentionInfoDao;
import com.frogs.ucenter.dao.UserHonorLevelDao;
import com.frogs.ucenter.dao.UserHonorLogDao;
import com.frogs.ucenter.dao.UserHonorScoreDao;
import com.frogs.ucenter.dao.UserHonorScoreLogDao;
import com.frogs.ucenter.dao.UserOpenPlatformInfoDao;
import com.frogs.ucenter.entity.UserHonorLevel;
import com.frogs.ucenter.entity.UserHonorLog;
import com.frogs.ucenter.entity.UserHonorScore;
import com.frogs.ucenter.entity.UserHonorScoreLog;
import com.frogs.ucenter.util.wechat.WechatMessageSend;
import com.frogs.ucenter.v1.request.UserHonorListRequest;
import com.frogs.ucenter.v1.response.DefaultResponse;
import com.frogs.ucenter.v1.response.ListResponse;
import com.frogs.ucenter.v1.service.UserHonorService;
import com.frogs.ucenter.v1.util.ApiConstants;

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Service(ApiConstants.VERSION+"userHonorService")
public class UserHonorServiceImpl implements UserHonorService {
	
	private static final Logger log = LoggerFactory.getLogger(UserHonorServiceImpl.class);
	
	@Resource
	private UserHonorScoreDao userHonorScoreDao;
	@Resource
	private UserHonorScoreLogDao userHonorScoreLogDao;
	@Resource
	private UserHonorLogDao userHonorLogDao;
	@Resource
	private UserHonorLevelDao userHonorLevelDao;
	@Resource
	private RequestApiHelper requestApiHelper;
	@Resource
	private UserOpenPlatformInfoDao userOpenPlatformInfoDao;
	@Resource
	private UserAttentionInfoDao userAttentionDao;
	@Resource
	private WechatMessageSend wechatMessageSend;
	
	@Override
	//@Async
	public Response insertUserHonorScore(Integer userId,Integer honorType,Integer honorScore,String detail,Integer targetUserId,Integer applicablePlatformId,boolean flag) throws Exception {
		DefaultResponse response = new DefaultResponse();
		Map<String,Object> params = new HashMap<String , Object>();
		if (targetUserId > 0) {
				try {
					params.put("eqHonorType", honorType);
					params.put("eqUserId", userId);
					params.put("eqDetail", detail);
					params.put("eqTargetUserId",targetUserId);
					if (flag) {
						params.put("eqCreateTime", "");
					}
					PageList<UserHonorScoreLog> userHonorScoreLogs = userHonorScoreLogDao.selectByMap(params, 0, 999, false);
					if(userHonorScoreLogs.size()==0){
						int userHonorScore = 0;
						UserHonorScore uhs = null;
						params.clear();
						params.put("eqUserId", userId);
						params.put("eqHonorType", honorType);
						PageList<UserHonorScore> userHonorScores = userHonorScoreDao.selectByMap(params, 0, 999, false);
						if(userHonorScores.size()>0){
							uhs = userHonorScores.get(0);
							userHonorScore = uhs.getHonorScore()+honorScore;
							uhs.setHonorScore(userHonorScore);
							userHonorScoreDao.update(uhs);
							log.info("UserHonorServiceImpl.insertUserHonorScore=userID："+ userId+" 更新荣誉值");
						}else{
							uhs = new UserHonorScore();
							uhs.setHonorScore(honorScore);
							userHonorScore = honorScore;
							uhs.setHonorType(honorType);
							uhs.setUserId(userId);
							userHonorScoreDao.insert(uhs);
							log.info("UserHonorServiceImpl.insertUserHonorScore=userID："+ userId+" 新增荣誉值");
						}
						UserHonorScoreLog usl = new UserHonorScoreLog();
						usl.setCreateTime(new Date());
						usl.setDetail(detail);
						usl.setHonorScore(honorScore);
						usl.setHonorType(honorType);
						usl.setUserId(userId);
						usl.setTargetUserId(targetUserId);
						userHonorScoreLogDao.insert(usl);
						//判断是否升级发消息
						this.upgrade2UserHonor(honorType, userId, userHonorScore,applicablePlatformId);
						
						response.setTip("添加成功");
					}else{
						response.setTip("添加失败,已有记录存在");
						response.setCode(ApiResultEnum.FAIL.getId());
					}
					
				} catch (Exception e) {
					log.error("func[{}] request[{}] exception[{}] desc[fail]",
							new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
								Arrays.deepToString(e.getStackTrace()) });
					throw new ServiceOperationException("请求处理失败：" + e.getMessage());
				}
		}else {  //挂号，购药，绑定事件
			try {
				int userHonorScore = 0;
				UserHonorScore uhs = null;
				params.clear();
				params.put("eqUserId", userId);
				params.put("eqHonorType", honorType);
				PageList<UserHonorScore> userHonorScores = userHonorScoreDao.selectByMap(params, 0, 999, false);
				if(userHonorScores.size()>0){
					uhs = userHonorScores.get(0);
					userHonorScore = uhs.getHonorScore()+honorScore;
					uhs.setHonorScore(userHonorScore);
					userHonorScoreDao.update(uhs);
					log.info("UserHonorServiceImpl.insertUserHonorScore=userID："+ userId+" 更新荣誉值");
				}else{
					uhs = new UserHonorScore();
					uhs.setHonorScore(honorScore);
					userHonorScore = honorScore;
					uhs.setHonorType(honorType);
					uhs.setUserId(userId);
					userHonorScoreDao.insert(uhs);
					log.info("UserHonorServiceImpl.insertUserHonorScore=userID："+ userId+" 新增荣誉值");
				}
				UserHonorScoreLog usl = new UserHonorScoreLog();
				usl.setCreateTime(new Date());
				usl.setDetail(detail);
				usl.setHonorScore(honorScore);
				usl.setHonorType(honorType);
				usl.setUserId(userId);
				usl.setTargetUserId(targetUserId);
				userHonorScoreLogDao.insert(usl);
				//判断是否升级发消息
				this.upgrade2UserHonor(honorType, userId, userHonorScore,applicablePlatformId);
				
				response.setTip("添加成功");
			} catch (Exception e) {
				log.error("func[{}] request[{}] exception[{}] desc[fail]",
						new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
							Arrays.deepToString(e.getStackTrace()) });
				throw new ServiceOperationException("请求处理失败：" + e.getMessage());
			}
		}
		return response;
	}
	
	/**
	 * 判断用户是否升级并且发消息
	 * @param honorType 荣誉类型
	 * @param userId 用户ID
	 * @param score 用户当前分值
	 */
	public void upgrade2UserHonor(int honorType,int userId,int score,int openPlatformId){
		boolean flag = false;
		//1.查询所有等级
		Map<String,Object> params = new HashMap<String , Object>();
		params.put("eqHonorType", honorType);
		params.put("orderByClause", " honor_level asc ") ;
		PageList<UserHonorLevel> userHonorLevels = userHonorLevelDao.selectByMap(params, 0, 999, false);
		UserHonorLevel uhl = null;
		if(userHonorLevels.size()>0){
			//2.用户目前的等级信息
			params.clear();
			params.put("eqJoinUserId", userId);
			params.put("eqJoinHonorType", honorType);
			params.put("join", "");
			params.put("orderByClause", " t.level_id desc");
			PageList<UserHonorLog> userHonorLogs = userHonorLogDao.selectJoinByMap(params, 0, 999, false);
			UserHonorLog uhlog = null;
			if(userHonorLogs.size()>0){
				uhlog = userHonorLogs.get(0);
				log.info("用户当前最大的等级===="+JSONObject.toJSONString(uhlog)+" "+uhlog.getHonorLevel());
				for (Iterator iterator = userHonorLevels.iterator(); iterator.hasNext();) {
					UserHonorLevel userHonorLevel = (UserHonorLevel) iterator.next();
					if((userHonorLevel.getHonorLevel()-uhlog.getHonorLevel())==1){
						if(score >= userHonorLevel.getLevelScore()){
							uhl = userHonorLevel;
							uhlog = new UserHonorLog(); 
							uhlog.setLevelId(uhl.getId());
							uhlog.setCreateTime(new Date());
							uhlog.setUserId(userId);
							uhlog.setHonorType(honorType);
							log.info("UserHonorServiceImpl.insertUserHonorScore=userID："+ userId+" 升级");
							userHonorLogDao.insert(uhlog);
							flag = true;
							break;
						}
					}
				}
			}else{//用户还没有等级
				//那当前分值比较等级列表最小的那个
				uhl = userHonorLevels.get(0);
				log.info("最小等级===="+JSONObject.toJSONString(uhl)+" score="+score);
				if(score >= uhl.getLevelScore() ){
					uhlog = new UserHonorLog();
					uhlog.setCreateTime(new Date());
					uhlog.setHonorType(honorType);
					uhlog.setLevelId(uhl.getId());
					uhlog.setUserId(userId);
					userHonorLogDao.insert(uhlog);
					log.info("UserHonorServiceImpl.insertUserHonorScore=userID："+ userId+" 0升级");
					flag = true;
				}
			}
			if(flag){
				this.sendMessage(userId, openPlatformId,uhl.getId());
			}
		}
		
	}

	@Override
	public Response getUserHonorList(Request request) throws Exception {
		ListResponse<UserHonorLog> response = new ListResponse<UserHonorLog>();
		try {
			UserHonorListRequest uhl = (UserHonorListRequest)request;
			Map<String,Object> params = new HashMap<String , Object>();
			params.put("eqJoinUserId", uhl.getUserId());
			params.put("eqJoinHonorType", uhl.getHonorType());
			params.put("join", "");
			params.put("orderByClause", "honor_level  desc");
			PageList<UserHonorLog> userHonorLogs = userHonorLogDao.selectJoinByMap(params, 0, 999, false);
			
			if (userHonorLogs!=null && userHonorLogs.size()>0) {
				response.setList(userHonorLogs);
				log.info("用户"+uhl.getUserId()+"的荣誉信息："+response);
			}else {
				
				UserHonorLog userHonorLog = new UserHonorLog();
				
				UserHonorScore userHonorScore = userHonorScoreDao.selectUserScoreByUserId(uhl.getUserId());
				userHonorLog.setDetail("新人");
				userHonorLog.setLevelName("新人");
				userHonorLog.setUserId(uhl.getUserId());
				if (userHonorScore!=null) {
					userHonorLog.setHonorScore(userHonorScore.getHonorScore()+"");
				}else {
					userHonorLog.setHonorScore("0");
				}
				userHonorLogs.add(userHonorLog);
				response.setList(userHonorLogs);
			}
			log.info("用户"+uhl.getUserId()+"的荣誉信息："+response); 
		}catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		log.info(JSON.toJSONString(response)); 
		return response;
	}

	@Override
	public Response getUserLevelDetail(Request request) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	
	/**
	 * 判断两人是否为家人关系
	 * @param userId 发起提醒用户
	 * @param followedUserId  接收提醒用户
	 * @return
	 */
	/*private boolean isFamily(int userId,int followedUserId){
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("eqFollowUserId", userId);
		params.put("eqFollowedUserId", followedUserId);
		params.put("eqStatus", 1);
		PageList<UserAttentionInfo> uas = userAttentionDao.selectByMap(params, 0, 999, false);
		if(uas.size()>0){
			return true;
		}else{
			return false;
		}
	}*/
	
	private void sendMessage(int userId,int applicablePlatformId,int userHonorLevelId){
		UserHonorLevel uhl = userHonorLevelDao.selectById(userHonorLevelId);
		String remark = "您的爱心值爆表啦，快去分享给小伙伴们吧！点我查看";
		String url = "http://w.frogshealth.com/user/honor/prize?detail="+uhl.getDetail()+"&userId="+userId;
		String keyword = "爱心值升级通知";
		String messageStr = TemplateUtil.convert(url, keyword, remark);
		wechatMessageSend.send(userId, userId, messageStr, applicablePlatformId);
		log.info("sendMessage===="+"爱心值升级：userId:"+userId+",detail:"+uhl.getDetail());
	}
	
	
}